package cn.kgc.controller;

import cn.kgc.pojo.Category;
import cn.kgc.pojo.NewsDetail;
import cn.kgc.service.CategoryServcie;
import cn.kgc.service.CategoryServiceImpl;
import cn.kgc.service.NewsDetailService;
import cn.kgc.service.NewsDetailServiceImpl;
import cn.kgc.util.MD5Util;
import cn.kgc.util.PageSupport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

public class NewsServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String type= request.getParameter("type");
        NewsDetailService newsService = new NewsDetailServiceImpl();
        CategoryServcie categoryServcie = new CategoryServiceImpl();
        //获取项目上下文web请求的根路径
        String path= request.getContextPath();

        if(type.equals("list")) {
            String categoryId = request.getParameter("categoryId");
            String title = request.getParameter("title");
            //获取前端传过来的页码
            String pageNo = request.getParameter("pageNo");
            System.out.println(pageNo);
            //获取分类
            List<Category> list = categoryServcie.getCategoryList();

            //获取分页数据
            PageSupport pageSupport = new PageSupport();
            Integer id = null;
            if (categoryId != null) {
                id = Integer.parseInt(categoryId);
                if (id == 0) {
                    id = null;
                }
            }
            //如果有传值则按照传过来的页码，否则按照默认1
            if (pageNo != null) {
                pageSupport.setPageNo(Integer.parseInt(pageNo));
            }
            pageSupport = newsService.getNewsDetailListByPage(title, id, pageSupport);
            //打包
            request.setAttribute("page", pageSupport);
            //数据回显
            request.setAttribute("title", title);
            request.setAttribute("categoryId", categoryId);
            request.setAttribute("categorylist", list);
            //转发
            request.getRequestDispatcher("/day04/newsDetailList.jsp").forward(request, response);

        }else if(type.equals("add")){
            //接收前端的请求，请求封装数据，对象

            boolean bRet = false;
            boolean bUpload = false;
            String uploadFileName = "";
            String fieldName = "";
            NewsDetail news = new NewsDetail();
            //解析请求之前先判断请求类型是否为文件上传类型
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //指定上传位置
            String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");

            File saveDir = new File(uploadFilePath);
            System.out.println("绝对路径："+saveDir.getAbsoluteFile());
            System.out.println("uploadFilePath"+uploadFilePath);
            if(isMultipart){
                //创建文件上传核心类
                FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
                ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
                try{
                    //处理表单请求
                    List<FileItem> items = upload.parseRequest(request);
                    Iterator<FileItem> iter = items.iterator();
                    while(iter.hasNext()){
                        FileItem item = (FileItem)iter.next();
                        if(item.isFormField()){// 如果是普通表单控件
                            fieldName = item.getFieldName();// 获得该字段名称
                            if(fieldName.equals("title")){
                                news.setTitle(item.getString("UTF-8"));//获得该字段值
                            }else if(fieldName.equals("categoryId")){
                                news.setCategoryId(Integer.parseInt(item.getString()));
                            }else if(fieldName.equals("summary")){
                                news.setSummary(item.getString("UTF-8"));
                            }else if(fieldName.equals("newscontent")){
                                news.setContent(item.getString("UTF-8"));
                            }else if(fieldName.equals("author")){
                                news.setAuthor(item.getString("UTF-8"));
                            }
                        }else{// 如果为文件域
                            String fileName = item.getName();// 获得文件名(全路径)
                            if(fileName != null && !fileName.equals("")){
                               String suffix= fileName.substring(fileName.lastIndexOf("."));
                               String name= MD5Util.getMd5(fileName,8)+MD5Util.getRandomCode()+suffix;
                                File fullFile = new File(name);
                                File saveFile = new File(uploadFilePath,fullFile.getName());//将文件保存到指定的路径
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();
                                news.setPicPath(uploadFileName);
                                bUpload = true;
                            }

                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }

            }
            System.out.println("上传成功之后的文件名：" + news.getPicPath());
            //调用后台的方法，将新闻信息插入数据库中

            //调用service层 ，入参:对象  返回int
            int rs= newsService.addNews(news);

            //判断int是否大于0，则添加成功，否则添加失败
            if(rs>0){
                //如果添加成功，重定向还是转发？ 重定向
                response.sendRedirect(path+"/news?type=list");
            }else{
                request.setAttribute("error","添加失败");
                request.getRequestDispatcher("/day04/createnews.jsp").forward(request,response);
            }
        }else if(type.equals("update")){


        }else if(type.equals("view")){
            String id=request.getParameter("id");
            NewsDetail newsDetail= newsService.getNewsDetailById(Integer.parseInt(id));
            Category category =categoryServcie.getCategoryById(newsDetail.getCategoryId());
            request.setAttribute("news",newsDetail);
            request.setAttribute("categoryName",category.getName());
            request.getRequestDispatcher("/day04/newsdetail.jsp").forward(request, response);


        }else if(type.equals("delete")){
            int delid=request.getParameter("id")==null?null:Integer.parseInt(request.getParameter("id"));
            boolean rs= newsService.deleteNews(delid);
            if(rs==true){
                response.sendRedirect(path+"/news?type=list");
            }else{
                response.sendRedirect(path+"/news?type=list");
            }
        }else if(type.equals("ds")){
            ServletContext context =request.getSession().getServletContext();
            DataSource ds= (DataSource) context.getAttribute("datasource");
            try {
                System.out.println(ds.getConnection());
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }


}
